package com.luobo.pcsdepositmanage;

import com.luobo.pcsdepositmanage.pojo.basic.PcsDeposit;
import com.luobo.pcsdepositmanage.pojo.createacsfile.AcsFile;
import com.luobo.pcsdepositmanage.pojo.createacsfile.AcsInOutDescribe;
import com.luobo.pcsdepositmanage.pojo.databasetest.PcsDepositFile;
import com.luobo.pcsdepositmanage.pojo.databasetest.PcsInOutDescribe;
import com.luobo.pcsdepositmanage.service.databasetest.PcsDepositFileService;
import com.luobo.pcsdepositmanage.service.databasetest.PcsInOutDescribeService;
import com.luobo.pcsdepositmanage.util.ExcelOperationUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.IOException;
import java.util.*;

@SpringBootTest
public class pcsdepositDatabase {

    private static final Logger LOGGER = LoggerFactory.getLogger(PcsdepositmanageApplicationTests.class);

    @Autowired
    private PcsInOutDescribeService pcsInOutDescribeService;
    @Autowired
    private PcsDepositFileService pcsDepositFileService;

    private List<PcsInOutDescribe> pcsInOutDescribeList = new ArrayList<>();

    private List<Map<Integer,Object>> sysDictmapList;
    private List<Map<Integer,Object>> acsFileList;
    private Map<String,Object> acsNameMap = new HashMap<>();

    private List<PcsDepositFile> pcsDepositFileList = new ArrayList<>();
    private List<PcsInOutDescribe> PcsInOutDescribeList = new ArrayList<>();

    Map<Integer,String> converMap = new HashMap<>();

    private String filedir;
    private String resultFileName = "test1.xlsx";
    @Test
    public void importDataFromACSFile(){

//        读取文件
//        生成List<PcsDepositFile>
//        生成List<PcsInOutDescribe>
        readDataFromAcsFile();


//        将List<PcsInOutDescribe>写入数据库
        this.pcsDepositFileService.batchAddData(this.pcsDepositFileList);
        this.pcsInOutDescribeService.batchAddData(this.pcsInOutDescribeList);

    }


    public void readDataFromAcsFile(){
        this.converMap.put(1,"Y_1");
        this.converMap.put(2,"D_4");
        this.converMap.put(3,"Y_3");
        this.converMap.put(4,"D_1");
        this.converMap.put(5,"D_2");
        this.converMap.put(6,"D_3");
        this.converMap.put(7,"Y_4");
        this.converMap.put(8,"Y_8");
        this.converMap.put(9,"Y_9");

        Map<String,Object> paraMap = new HashMap<>();
        try {
            this.filedir = "/Users/liuminghao/Documents/tmp";
            String filename = "esb模板.xlsx";
            String sheetname = "系统级字典项";

            int headrownum = 3;
            paraMap.put("filedir",filedir);
            paraMap.put("filename",filename);
            paraMap.put("sheetname",sheetname);
            paraMap.put("headrownum",headrownum);
//获取数据字典
//            this.sysDictmapList = EasyExcelUtils.noModelReadEasyExcel(paraMap);
            this.sysDictmapList = ExcelOperationUtil.readExcelFromFileForMapToListMap(paraMap);
//            this.workbook = ExcelOperationUtil.getWorkbookFromExcel(filedir+"/"+filename);

            filename = "acsFileList.xlsx";
            sheetname = "是否生成";
            headrownum = 1;
            paraMap.put("filename",filename);
            paraMap.put("sheetname",sheetname);
            paraMap.put("headrownum",headrownum);

//            this.acsFileList = EasyExcelUtils.noModelReadEasyExcel(paraMap);
            this.acsFileList = ExcelOperationUtil.readExcelFromFileForMapToListMap(paraMap);
            for (int i = 0; i < this.acsFileList.size(); i++) {
                Object col1Object = this.acsFileList.get(i).get(0);
                Object col2Object = this.acsFileList.get(i).get(1);
                Object col3Object = this.acsFileList.get(i).get(2);
                Object col4Object = this.acsFileList.get(i).get(3);
                Object col5Object = this.acsFileList.get(i).get(4);
                Map<String,String> tempMap = new HashMap<>();

                if(col2Object != null){
                    tempMap.put("acsIsCreate",(String)col2Object);
                }else{
                    tempMap.put("acsIsCreate","否");
                }
                if(col3Object != null){
                    tempMap.put("acsDepositCate",(String)col3Object);
                }else{
                    tempMap.put("acsDepositCate","");
                }
                if(col4Object != null){
                    tempMap.put("acsDepositIdenty",(String)col4Object);
                }else{
                    tempMap.put("acsDepositIdenty","");
                }
                if(col5Object != null){
                    tempMap.put("acsDepositSyscode",(String)col5Object);
                }else{
                    tempMap.put("acsDepositSyscode","");
                }
                if(col1Object != null && col1Object.toString().length()>0){
                    this.acsNameMap.put((String)col1Object,tempMap);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        String filedir = "/Users/liuminghao/Documents/tmp/ACSFile";
        File file = new File(filedir);
        fileOperation(file);
    }

    public boolean isCreateAcs(File file){
        boolean isCreateFlag = false;

        String tempFileName = file.getName();
        String[] tempStringArr = tempFileName.split("_");
        if(tempStringArr.length>3){
            String acsName = tempStringArr[3];
            if(this.acsNameMap.containsKey(acsName)){
                Map<String,String> tempString = (Map<String, String>) this.acsNameMap.get(acsName);
                if(tempString.get("acsIsCreate").equals("是")){
                    isCreateFlag = true;
                }
            }
        }
        return isCreateFlag;
    }

    public void fileOperation(File file) {
        try {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    fileOperation(f);
                }
            } else {
                int lastIndexOf = file.getName().lastIndexOf(".");
                //获取文件的后缀名 .jpg
                String suffix = file.getName().substring(lastIndexOf);
                LOGGER.info("当前文件扩展名为：{}",suffix);
                if(suffix.equals(".xlsx")){
//                    System.out.println(file.getName());
                    if(isCreateAcs(file)){
                        operaAcsFile(file);
                    }else {
                        LOGGER.info("文件：{}，不再生成列表acsFileList.xlsx中",file.getName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }


    public void operaAcsFile(File file){
        Map<String,Object> paraMap = new HashMap<>();
//        配置读取excel参数
        String filedir = null;
        filedir = file.getParentFile().getPath();
        String filename = file.getName();
        paraMap.put("filedir", filedir);
        paraMap.put("filename", filename);

        Workbook tempworkbook = null;
        try {
            tempworkbook = ExcelOperationUtil.getWorkbookFromExcel(file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Map<Integer, Object>> acsmapList = null;
        List<Integer> areaIntList = new ArrayList<>();
        List<Map<Integer, Object>> acsmapListQT = null;
        Iterator<Sheet> sheetIterator = tempworkbook.sheetIterator();
        while (sheetIterator.hasNext()) {
            Sheet sheet = sheetIterator.next();
            String sheetname = sheet.getSheetName();

            if(sheetname.trim().equals("ACS")){
                int headrownum = 0;

                paraMap.put("sheetname", sheetname);
                paraMap.put("headrownum", headrownum);

                LOGGER.info("设置读取文件目录:{}", paraMap.get("filedir"));
                LOGGER.info("设置读取文件名称:{}", paraMap.get("filename"));
                LOGGER.info("设置读取文件sheet页:{}", paraMap.get("sheetname"));
                LOGGER.info("设置读取文件起始行号:{}", paraMap.get("headrownum"));
//        System.out.println(paraMap);
//获取ACS定义文件数据
                try {
//                    acsmapList = EasyExcelUtils.noModelReadEasyExcel(paraMap);
                    acsmapList = ExcelOperationUtil.readExcelFromFileForMapToListMap(paraMap);
                    LOGGER.info("读取Sheet页:{},获取到数据:{}行", paraMap.get("sheetname"), acsmapList.size());

                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.info(e.getStackTrace().toString());

                }
//读取区域范围
                for (int i = 0; i < acsmapList.size(); i++) {
                    if (acsmapList.get(i).get(0) != null && acsmapList.get(i).get(0).toString().length()>0) {
//                System.out.println(acsmapList.get(i).get(0));
                        areaIntList.add(i);
                    }
                }
//        System.out.println(areaIntList);
            }else if (sheetname.trim().equals("ACS-其他属性")){
//                sheetname = "ACS-其他属性";
                int pageNum = tempworkbook.getSheetIndex(sheet);
                paraMap.put("sheetname", pageNum);
                LOGGER.info("设置读取文件sheet页:{}", paraMap.get("sheetname"));
//获取ACS定义文件ACS-其他数据
                try {
//                    acsmapListQT = EasyExcelUtils.noModelReadEasyExcel(paraMap);
                    acsmapListQT = ExcelOperationUtil.readExcelFromFileForMapToListMap(paraMap);
                    LOGGER.info("读取Sheet页:{},获取到数据:{}行", paraMap.get("sheetname"), acsmapListQT.size());
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.info(e.getStackTrace().toString());
                }
            }

        }

        try {
            if(tempworkbook != null){
                tempworkbook.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        PcsDepositFile pcsDepositFile = convertAcsFileFromList(acsmapList, areaIntList, acsmapListQT);
        pcsDepositFile.setPcsFileDir(this.filedir);
        pcsDepositFile.setPcsFileName(filename);
        this.pcsDepositFileList.add(pcsDepositFile);

        List<PcsInOutDescribe> pcsInDescribeList = convertAcsInOutDescribeFromList(pcsDepositFile.getPcsDepositCode(),acsmapList, areaIntList,4,5,"in");
        List<PcsInOutDescribe> pcsOutDescribeList = convertAcsInOutDescribeFromList(pcsDepositFile.getPcsDepositCode(),acsmapList, areaIntList,4,5,"out");

        this.pcsInOutDescribeList.addAll(pcsInDescribeList);
        this.pcsInOutDescribeList.addAll(pcsOutDescribeList);

//
    }


    public PcsDepositFile convertAcsFileFromList(List<Map<Integer,Object>> acsmapList,List<Integer> integerList,List<Map<Integer,Object>> acsmapListQT){
        PcsDepositFile pcsDepositFile = new PcsDepositFile();

        Object tempString = acsmapList.get(0).get(5);
        if(tempString != null && tempString.toString().length()>0){
            pcsDepositFile.setPcsDepositName((String) tempString);
//            LOGGER.info("当前处理PCS服务名称:{}",acsFile.getAcsDepositName());
        }else{
            pcsDepositFile.setPcsDepositName("未正确获取PCS服务名称");
            LOGGER.info("获取ACS服务名称错误");
        }

        tempString = null;
        tempString = acsmapList.get(0).get(3);
        if(tempString != null && tempString.toString().length()>0){
            pcsDepositFile.setPcsDepositCode((String) tempString);
            LOGGER.info("当前处理PCS服务编码:{}:当前处理PCS服务名称:{}",pcsDepositFile.getPcsDepositCode(),pcsDepositFile.getPcsDepositName());

        }else{
            pcsDepositFile.setPcsDepositCode("未正确获取PCS服务编码");
            LOGGER.info("获取ACS服务名称错误");
        }

        Map<String,String> tempMap = null;

        if(acsNameMap.containsKey(pcsDepositFile.getPcsDepositCode())){
            tempMap = (Map<String, String>) acsNameMap.get(pcsDepositFile.getPcsDepositCode());
            pcsDepositFile.setPcsDepositCate(tempMap.get("acsDepositCate"));
            pcsDepositFile.setPcsDepositIdenty(tempMap.get("acsDepositIdenty"));
            pcsDepositFile.setPcsDepositSyscode(tempMap.get("acsDepositSyscode"));
        }else {
            pcsDepositFile.setPcsDepositCate("");
            pcsDepositFile.setPcsDepositIdenty("");
        }

        tempString = null;
        tempString = acsmapList.get(1).get(1);
        if(tempString != null && tempString.toString().length()>0){
            pcsDepositFile.setPcsDepositDescribe((String)tempString);
        }else{
            pcsDepositFile.setPcsDepositDescribe("未正确获取PCS服务功能描述");
            LOGGER.info("未正确获取PCS服务功能描述");
        }
        tempString = null;
        tempString = acsmapList.get(3).get(1);
        if(tempString != null && tempString.toString().length()>0){
            pcsDepositFile.setPcsDepositText((String)tempString);
        }else{
            pcsDepositFile.setPcsDepositText("未正确获取PCS服务功能内容");
            LOGGER.info("未正确获取PCS服务功能内容");
        }

        if(pcsDepositFile.getPcsDepositSyscode() == null || pcsDepositFile.getPcsDepositSyscode().length() == 0){
            List<String> systemList = getAreaList(acsmapList,integerList,3,4,5);
            if(systemList!=null && systemList.size()>0){
                pcsDepositFile.setPcsDepositSyscode(String.join("|",systemList));
            }else{
                LOGGER.info("获取渠道列表为空");
                pcsDepositFile.setPcsDepositSyscode("渠道列表为空");
            }
        }

        tempString = null;
        if(acsmapListQT.size()>2 && acsmapListQT.get(2).size()>5){
            tempString = acsmapListQT.get(2).get(5);
        }
        if(tempString != null && tempString.toString().length()>0){
            pcsDepositFile.setPcsDepositSAF((String)tempString);
        }else{
            pcsDepositFile.setPcsDepositSAF("未正确获取PCS服务SAF属性内容");
            LOGGER.info("未正确获取PCS服务SAF属性内容");
        }

        return pcsDepositFile;
    }

    public List<PcsInOutDescribe> convertAcsInOutDescribeFromList(String pcsDepositCode,List<Map<Integer,Object>> acsmapList,List<Integer> integerList,int startNum ,int endNum,String inOutFlag){
        List<PcsInOutDescribe> pcsInOutDescribes = new ArrayList<>();


        int j = integerList.get(startNum);
        int k  = integerList.get(endNum);

        if(inOutFlag.equals("in")){
            LOGGER.info("读取并设置原始定义文件的输入内容");
        }else{
            LOGGER.info("读取并设置原始定义文件的输出内容");
        }

        for (int l = j+1; l < k; l++) {
            PcsInOutDescribe pcsInOutDescribe = new PcsInOutDescribe();
            pcsInOutDescribe.setPcsDepositCode(pcsDepositCode);

            Object tempString = acsmapList.get(l).get(1);
            if(tempString != null && tempString.toString().length()>0 && tempString.toString().length() < 5){
                pcsInOutDescribe.setOrderNum((Integer) tempString);
            }else {
                LOGGER.info("未正确获取序号");
                break;
//                acsInOutDescribe.setOrderNum(null);
            }

            tempString = null;
            tempString = acsmapList.get(l).get(2);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setEnName((String)tempString);
            }else {
                LOGGER.info("未正确获取英文名称");
                pcsInOutDescribe.setEnName(null);
            }
            tempString = null;
            tempString = acsmapList.get(l).get(3);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setChName((String)tempString);
            }else {
                LOGGER.info("未正确获取中文名称");
                pcsInOutDescribe.setChName(null);
            }
            tempString = null;
            tempString = acsmapList.get(l).get(4);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setIsRequired((String)tempString);
            }else {
                LOGGER.info("未正确获取是否必输");
                pcsInOutDescribe.setIsRequired(null);
            }
            tempString = null;
            tempString = acsmapList.get(l).get(5);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setDataDictCode((String)tempString);
            }else {
                LOGGER.info("未正确获取数据字典");
                if( pcsInOutDescribe.getChName() == null || pcsInOutDescribe.getChName().equals("SUBBEGIN") || pcsInOutDescribe.getChName().equals("SUBEND")  ){
                    pcsInOutDescribe.setDataDictCode(null);
                }else {
                    pcsInOutDescribe.setDataDictCode("申请中");
                }
            }
            tempString = null;
            tempString = acsmapList.get(l).get(6);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setDataDictTypeDescribe((String)tempString);
            }else {
                LOGGER.info("未正确获取数据格式");
                pcsInOutDescribe.setDataDictTypeDescribe(null);
            }
            tempString = null;
            tempString = acsmapList.get(l).get(7);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setTypeDescribe((String)tempString);
            }else {
                LOGGER.info("未正确获取数据类型");
                pcsInOutDescribe.setTypeDescribe(null);
            }
            tempString = null;
            tempString = acsmapList.get(l).get(8);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setAttributeDescribe((String)tempString);
            }else {
//                LOGGER.info("未正确获取栏位属性");
                pcsInOutDescribe.setAttributeDescribe(null);
            }
            tempString = null;
            tempString = acsmapList.get(l).get(9);
            if(tempString != null && tempString.toString().length()>0){
                pcsInOutDescribe.setRemarkDescribe((String)tempString);
            }else {
                LOGGER.info("未正确获取描述");
                pcsInOutDescribe.setRemarkDescribe(null);
            }

            pcsInOutDescribe = convertAreaListList(pcsInOutDescribe);

            if(inOutFlag.equals("in")){
                pcsInOutDescribe.setInOutFlag(0);
            }else if(inOutFlag.equals("out")){
                pcsInOutDescribe.setInOutFlag(1);
            }
            pcsInOutDescribe.setStatus(0);
            pcsInOutDescribes.add(pcsInOutDescribe);
        }

        return pcsInOutDescribes;

    }



    public PcsInOutDescribe convertAreaListList(PcsInOutDescribe pcsInOutDescribe){

        String chName = pcsInOutDescribe.getChName();
        if(chName != null && chName.length() > 0){
            List<String> sysDictList = getsysDict(chName);
            for (int j = 1; j < converMap.size()+1; j++) {
                String[] converMapAarry = converMap.get(j).split("_");
                if(converMapAarry[0].equals("Y")){
                    continue;
                }else if (converMapAarry[0].equals("D")){
                    int k = Integer.valueOf(converMapAarry[1])-1;
                    if(k < sysDictList.size()){
                        if(j == 2){
                            pcsInOutDescribe.setEnName(sysDictList.get(k));
                        }else if(j == 4){
                            pcsInOutDescribe.setDataDictCode(sysDictList.get(k));
                        }else if(j == 5){
                            pcsInOutDescribe.setDataDictTypeDescribe(sysDictList.get(k));
                        }else if(j == 6){
                            pcsInOutDescribe.setDataType(sysDictList.get(k));
                        }
                    }else{
                        continue;
                    }

                }
            }
        }

        return pcsInOutDescribe;
    }


    public List<String> getsysDict(String name){

//        sysDictmapList
        List<String> sysDictList = new ArrayList<>();
        for (int i = 0; i < this.sysDictmapList.size(); i++) {
            if(this.sysDictmapList.get(i).get(4).equals(name)){

                Object tempString = null;
                tempString = this.sysDictmapList.get(i).get(0);
                if(tempString!=null && tempString.toString().length() > 0){
                    sysDictList.add((String)tempString);
                }else {
                    sysDictList.add(null);
                }
                tempString = this.sysDictmapList.get(i).get(17);
                if(tempString!=null && tempString.toString().length() > 0){
                    sysDictList.add((String)tempString);
                }else {
                    sysDictList.add(null);
                }
                tempString = this.sysDictmapList.get(i).get(15);
                if(tempString!=null && tempString.toString().length() > 0){
                    sysDictList.add((String)tempString);
                }else {
                    sysDictList.add(null);
                }
                tempString = this.sysDictmapList.get(i).get(19);
                if(tempString!=null && tempString.toString().length() > 0){
                    sysDictList.add((String)tempString);
                }else {
                    sysDictList.add(null);
                }

                break;
            }
        }
        return sysDictList;
    }

    private List<String> getAreaList(List<Map<Integer, Object>> acsmapList, List<Integer> integerList, int i, int i1,int i2) {

        int j = integerList.get(i);
        int k  = integerList.get(i1);

        List<String> stringList = new ArrayList<>();
        for (int l = j+1; l < k; l++) {
            stringList.add(acsmapList.get(l).get(i2).toString());
        }

        return stringList;

    }



}
